// pages/login/index.js
import {loginAction} from '../../services/index.js'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    phone:'',
    code:'',
    phoneErr:'',
    errMessage:'',
    topHeight:getApp().globalData.topHeight,
    isCheck:'',
    sendCodeMessage:'发送验证码'
  },
  close(){
    wx.navigateBack()
  },
  checkReg(){
    const phoneReg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
    const res = phoneReg.exec(this.data.phone)
    this.setData({
      isCheck:res
    })
  },
  sendCode(){
    this.checkReg();
    if(!this.data.isCheck){
      wx.showToast({
        title: '请输入手机号',
        duration: 1000,
        mask: true,
        icon:'error',
      })
    }else{
      let time = 5
      const sendTimer = setInterval(()=>{
        if(time===1){
          clearInterval(sendTimer)
          this.setData({
            sendCodeMessage:'发送验证码'
          })
          time = 5
        }else{
          this.setData({
            sendCodeMessage:`${--time}秒后重试`
          })
        }
      },1000)
    }
    
  },
  codeChange(e){  
    this.setData({
      code:e.detail
    })
  },
  phoneChange(e){
    this.setData({
      phone:e.detail
    })
    this.checkReg()
    if(!this.data.isCheck){
          this.setData({
      phoneErr:'手机号格式错误'
    })}else{
      this.setData({
        phoneErr:''
      })
    }
  },
  loginClick(){

    this.checkReg()
    if(!this.data.isCheck){
      this.setData({
        phoneErr:'手机号格式错误'
      })
    }

    if(!this.data.code){
      this.setData({
        errMessage:'请输入验证码'
      })
    }else{
      this.setData({
        errMessage:''
      })
      loginAction({mobile:this.data.phone,code:this.data.code}).then(res=>{
        if(res.data.token){
          wx.setStorageSync('token', res.data.token)
          wx.showToast({
            title: '登陆成功',
            duration: 2000,
            icon: 'success',
            mask: true,
            success: (res) => {
              if(res.errMsg === "showToast:ok"){
                wx.switchTab({
                  url: '/pages/profile/index',
                })
              }
            },
          })
        }
        wx.setStorageSync('hmtt_token', JSON.stringify(res.data))
      })
    }
  },
  

})